//
//  ColorUtility.m
//  Objc进阶Demo
//
//  Created by Don't update on 2018/7/17.
//  Copyright © 2018年 Don't update. All rights reserved.
//

#import "ColorUtility.h"

@implementation ColorUtility

+(UIColor *)colorWithHexString:(NSString *)stringToConvert{
    if(stringToConvert == nil || [stringToConvert isEqualToString:@""]){
        return  nil;
    }
    
    /*e9e9e9
     *NSString 是有序字符串
     *NSCharacterset是无需字符集合，主要用来判断已知字符串是否包含制定字符集，而不可以用来保存字符串。
     *stringByTrimmingCharactersInSet函数过滤字符串中的特殊符号 首先自己定义一个NSCharacterSet, 包含需要去除的特殊符号
     */
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]uppercaseString];
    
    //String should be 6 or 8 characters
    //if([cString length)> 6 return DEFAULT_VOID_COLOR;
    
    //strip 0X of it appears
    if([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    //if ([cString length] != 6) return DEFAULT_VOID_COLOR;
    // Separate into r,g,b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    //Scan values
    unsigned int r,g,b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
   
    
    return [UIColor colorWithRed:((float) r/ 255.0f) green:((float) g/255.0f) blue:((float) b/255.0f) alpha:1.0f];
}

@end
